package web.ro.msg.gillardon.businesstripplanner.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import web.ro.msg.gillardon.businesstripplanner.LoginBean;

public class LoginFilter implements Filter {

    /**
     * Checks if user is logged in. If not it redirects to the login.xhtml page.
     */
    @Override
    public void doFilter(final ServletRequest request,
	    final ServletResponse response, final FilterChain chain)
	    throws IOException, ServletException {

	LoginBean loginBean = (LoginBean) ((HttpServletRequest) request)
		.getSession().getAttribute("loginBeaan");

	if (loginBean == null || !"user".equals(loginBean.getName())) {

	    String contextPath = ((HttpServletRequest) request)
		    .getContextPath();
	    ((HttpServletResponse) response).sendRedirect(contextPath
		    + "/login.xhtml");

	}

	chain.doFilter(request, response);

    }

    @Override
    public void init(final FilterConfig config) throws ServletException {
	// Nothing to do here!
    }

    @Override
    public void destroy() {
	// Nothing to do here!
    }

}
